//
//  KKImagePickerManager.m
//  KKImagePickerController
//
//  Created by Mac mini on 16/1/20.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "KKImagePickerManager.h"

#import "KKImageGroupsViewController.h"

@interface KKImagePickerManager() <UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    
    UIViewController __weak *_kk_rootViewController;
    
    UINavigationController *_kk_navigationController;
    
    UIImagePickerController *_kk_imagePickerController;
}

@end

@implementation KKImagePickerManager

+ (instancetype)kk_defaultManager {
    
    static KKImagePickerManager *pickerManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pickerManager = [KKImagePickerManager new];
    });
    return pickerManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
        _kk_rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            _kk_imagePickerController = [UIImagePickerController new];
            _kk_imagePickerController.delegate = self;
            _kk_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        
        KKImageGroupsViewController *groupTableViewController = [KKImageGroupsViewController new];
        _kk_navigationController = [[UINavigationController alloc] initWithRootViewController: groupTableViewController];
        
        _kk_navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:18],NSFontAttributeName, nil];
        [_kk_navigationController.navigationBar setTitleTextAttributes:attributes];
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel target: self action: @selector(kk_dismiss)];
        item.tintColor = [UIColor colorWithRed:0.000 green:0.606 blue:1.000 alpha:1.000];
        groupTableViewController.navigationItem.title = @"相册";
        groupTableViewController.navigationItem.rightBarButtonItem = item;
        
        
//        [];
    }
    return self;
}

- (void)dealloc {
    
    
}

#pragma mark - UIActionSheetDelegate methods

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {
        case 0:
        {
            [self kk_takePictureFromCamera];
        }
            break;
        case 1:
        {
            [self kk_takePictureFromAlbum];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - UIImagePickerControllerDelegate methods

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSLog(@"info = %@", info);
    
    [picker dismissViewControllerAnimated: true completion: nil];
    
//    [[KKLoadingView sharedInstance] loadingViewShowTips: @"保存中..." andWithEnable: true];
//    UIImage* image = info[UIImagePickerControllerOriginalImage];
//    [self saveImageToAssetsLibraryWithImage: image];
}

#pragma mark - Private methods

- (void)kk_dismiss {
    
    [_kk_navigationController popToRootViewControllerAnimated: false];
    [_kk_navigationController dismissViewControllerAnimated: true completion: nil];
}

- (BOOL)kk_authStatusWithCamera {
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeVideo];
    
    switch (authStatus) {
        case AVAuthorizationStatusNotDetermined:
        {
            __weak typeof(self) weakSelf = self;
            [AVCaptureDevice requestAccessForMediaType: AVMediaTypeVideo completionHandler:^(BOOL granted) {
                
                if (granted) {
                    [weakSelf kk_takePictureFromCamera];
                }
            }];
            
            return false;
        }
            break;
        case AVAuthorizationStatusRestricted:
        case AVAuthorizationStatusDenied:
        {
            [KKImagePickerController kk_showErrorMessage: @"请在设备的\"设置-隐私-相机\"中允许访问相机权限"];
            return false;
        }
            break;
        default:
            break;
    }
    
    return true;
}

- (BOOL)kk_authStatusWithAlbum {
    
    if (KKDeviceVersion < 8.0) {
        
        ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
        switch (authStatus) {
            case ALAuthorizationStatusRestricted:
            case ALAuthorizationStatusDenied:
            {
                [KKImagePickerController kk_showErrorMessage: @"请在设备的\"设置-隐私-照片\"中允许访问相册权限"];
                return false;
            }
                break;
            default:
                break;
        }
    }
    else {
        
        PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
        switch (authStatus) {
            case PHAuthorizationStatusNotDetermined:
            {
                __weak typeof(self) weakSelf = self;
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    
                    if (status == PHAuthorizationStatusAuthorized) {
                        [weakSelf kk_takePictureFromAlbum];
                    }
                }];
                
                return false;
            }
                break;
            case PHAuthorizationStatusRestricted:
            case PHAuthorizationStatusDenied:
            {
                [KKImagePickerController kk_showErrorMessage: @"请在设备的\"设置-隐私-照片\"中允许访问相册权限"];
                return false;
            }
                break;
            default:
                break;
        }
    }
    

    return true;
}

#pragma mark - Public methods
- (void)kk_takePicture {
    
    if (_kk_rootViewController == nil) {
        _kk_rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    }
    
    if (KKDeviceVersion < 8.0) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle: @"选取照片" delegate: self cancelButtonTitle: @"取消" destructiveButtonTitle: nil otherButtonTitles: @"拍照",@"相册", nil];
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [actionSheet showInView: window];
        return;
    }
    else {
        
        __weak typeof(self) weakSelf = self;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle: @"选取照片" message: nil preferredStyle: UIAlertControllerStyleActionSheet];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle: @"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction: cancelAction];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [weakSelf kk_takePictureFromCamera];
        }];
        [alertController addAction: action1];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle: @"相册" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [weakSelf kk_takePictureFromAlbum];
        }];
        [alertController addAction: action2];

        [_kk_rootViewController presentViewController: alertController animated: true completion: nil];
    }
}

- (void)kk_takePictureFromCamera {
    
    if (![self kk_authStatusWithCamera]) {
        return;
    }
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] && _kk_imagePickerController == nil) {
        _kk_imagePickerController = [UIImagePickerController new];
        _kk_imagePickerController.delegate = self;
        _kk_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    
    if (_kk_imagePickerController == nil) {
        
        [KKImagePickerController kk_showErrorMessage: @"设置暂不支持拍照功能"];
        return;
    }
    
    [_kk_rootViewController presentViewController: _kk_imagePickerController animated: true completion: nil];
}

- (void)kk_takePictureFromAlbum {
    
    if (![self kk_authStatusWithAlbum]) {
        return;
    }
    
    [_kk_rootViewController presentViewController: _kk_navigationController animated: true completion: nil];
}

@end
